package org.example.foodhealth.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import org.example.foodhealth.bean.UserLogin;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;

@Component
public class JwtTokenUtils {

    //private static final String SECRET_KEY = "fhdak4ngaIGGJLHJKLGfajlgmlkwiosgnleEj3l";
    private static final Key SECRET_KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode("fhdak4ngaIGGJLHJKLGfajlgmlkwiosgnleEj3lnidsohgm3JDOH13efsdJROIEUMLJD"));
    private static final long EXPIRATION_TIME = 24 * 60 * 60 * 1000; // 24小时

    // 生成 Token
    public static String generateToken(UserLogin user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("phone", user.getPhone());

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(user.getPhone())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    // 解析 Token
    public static Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build() // 需要调用 build()
                .parseClaimsJws(token)
                .getBody();
    }

    // 从 Token 获取手机号
    public static String getPhoneFromToken(String token) {
        return parseToken(token).getSubject();
    }

    //从JWT Token获取userId
    public static Long getUserIdFromToken(String token) {
        try {
            Claims claims = Jwts.parserBuilder() // 使用 parserBuilder
                    .setSigningKey(SECRET_KEY) // 直接使用 SECRET_KEY
                    .build() // 需要调用 build()
                    .parseClaimsJws(token)
                    .getBody();
            return Long.parseLong(claims.get("id").toString()); // 解析 userId
        } catch (Exception e) {
            return null; // 解析失败
        }
    }

    //从Http请求头获取Token,解析userId
    public static Long getUserIdFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return null;
        }
        return getUserIdFromToken(token.substring(7)); // 去掉 "Bearer "
    }
}
